﻿using System;
using System.Net;
using System.Runtime.Serialization;

namespace ThePresenter.Net.NetCom
{
	[Serializable]
	public class ServerInfo : ISerializable
	{
		public static TimeSpan InfoTimeout = new TimeSpan(2 * ThePresenter.Properties.Settings.Default.ServerBeaconTime.Ticks);
		public Guid Guid = Guid.Empty;
		public String Name = String.Empty;
		public IPEndPoint ServerEndPoint = null;
		public DateTime TTL = DateTime.Now;

		public Boolean IsValid
		{
			get { return (this.TTL > DateTime.Now); }
		}

		public ServerInfo(Guid _guid, String _name, IPEndPoint _ep)
		{
			this.Guid = _guid;
			this.Name = _name;
			this.ServerEndPoint = _ep;
		}

		#region ISerializable Members

		public ServerInfo(SerializationInfo info, StreamingContext ctxt)
		{
			this.Guid = (Guid)info.GetValue("Guid", typeof(Guid));
			this.Name = (String)info.GetValue("Name", typeof(String));
			this.ServerEndPoint = (IPEndPoint)info.GetValue("ServerEndPoint", typeof(IPEndPoint));
		}

		public void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if ((Guid == Guid.Empty) || (Name == String.Empty) || (ServerEndPoint == null))
				throw new MissingFieldException();

			info.AddValue("Guid", Guid);
			info.AddValue("Name", Name);
			info.AddValue("ServerEndPoint", ServerEndPoint);
		}

		#endregion

		public override bool Equals(object obj)
		{
			if (obj is ServerInfo)
			{
				return ((ServerInfo)obj).Guid.Equals(this.Guid);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override string ToString()
		{
			return this.Name;
		}
	}
}
